#include "app_mqtt.h"

static MQTTClient mqttClient;
static MQTTClient_connectOptions mqttConnectOptions = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static int (*recvCallback)(char *json) = NULL;


void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
}

// 接收到远程消息的回调函数
//返回值为1表示接收到数据成功
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;
    if (recvCallback != NULL)
    {
        result = (recvCallback((char *)message->payload)) == 0?1:0;
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

// 连接断开回调函数
void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("   cause: %s\n", cause);
}

/**
 * @brief MQTT客户端初始化
 * 
 * @return int 
 */
int app_mqtt_init(void){
    //1.创建MQTT客户端
    if (MQTTClient_create(&mqttClient, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTTClient_create failed");
        MQTTClient_destroy(&mqttClient);
        return -1;
    }
    //2.设置回调函数
    if (MQTTClient_setCallbacks(mqttClient, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTTClient_setCallbacks failed");
        MQTTClient_destroy(&mqttClient);
        return -1;
    }
    //3.连接服务器
    if (MQTTClient_connect(mqttClient, &mqttConnectOptions) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTTClient_connect failed");

        MQTTClient_destroy(&mqttClient);
        return -1;
    }
    //4.订阅主题
    if (MQTTClient_subscribe(mqttClient, TOPIC_RTG, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTTClient_subscribe failed");
        MQTTClient_disconnect(mqttClient, 10000);
        MQTTClient_destroy(&mqttClient);
        return -1;
    }
    return 0;
}

/**
 * @brief MQTT客户端发送数据
 * 
 * @param msg 
 * @return int 
 */
int app_mqtt_send(char *msg){
    pubmsg.payload = msg;
    pubmsg.payloadlen = strlen(msg);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(mqttClient, TOPIC_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTTClient_publishMessage failed");
        return -1;
    }
    
}

/**
 * @brief MQTT客户端关闭
 * 
 * @return int 
 */
void app_mqtt_close(void){
    MQTTClient_unsubscribe(mqttClient, TOPIC_RTG);
    MQTTClient_disconnect(mqttClient, 10000);
    MQTTClient_destroy(&mqttClient);
}

/**
 * @brief 注册用来处理远程消息的回调函数
 * 
 * @param callback 
 */
void app_mqtt_registerRecvCallback(int (*callback)(char *json)){
    recvCallback = callback;
}